package com.example.d7_method_references;

import com.example.d5_arrays.Student;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 目标：了解静态方法引用,实例方法引用,简化Lambda表达式
 */
public class Test1 {
    public static void main(String[] args) {
        Student[] students = new Student[4];
        students[0] = new Student("蜘蛛精", 169.5, 23);
        students[1] = new Student("紫霞", 163.8, 26);
        students[2] = new Student("紫霞", 163.8, 26);
        students[3] = new Student("至尊宝", 167.5, 24);

        // 原始方法,对数组中的学生对象,按照年龄进行排序
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge() - o2.getAge(); // 按照年龄升序排序
            }
        });

        // 使用lambda表达式简化后的形式
        // Arrays.sort(students, (o1, o2) -> o1.getAge() - o2.getAge());
        // Arrays.sort(students, Comparator.comparingInt(Student::getAge));

        // o1.getAge() - o2.getAge()这段代码外面在CompareByData类中定义了一个静态方法,所以可以通过这个方式实现
        // Arrays.sort(students, (o1, o2) -> CompareByData.compareByAge(o1, o2));

        // 静态方法引用：类名::方法名
        // Arrays.sort(students, CompareByData::compareByAge);
        // 还可以直接简化
        Arrays.sort(students, Comparator.comparingInt(Student::getAge));

        // 降序排序
        // Arrays.sort(students, (o1, o2) -> o2.getAge() - o1.getAge());
        CompareByData compareByData = new CompareByData();

        // Arrays.sort(students, (o1, o2) -> compareByData.compareByAgeDesc(o1, o2));
        // 实例方法引用：对象名::方法名
        Arrays.sort(students, compareByData::compareByAgeDesc);

        // 输出集合信息
        System.out.println(Arrays.toString(students));
    }
}

